//
//  RABookMallHeaderView.m
//  ReadApp
//
//  Created by 飞猪 on 2018/11/7.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "RABookMallHeaderView.h"
#import "RABookMallHeaderCell.h"
#import "RABookFaceModel.h"

static CGFloat const CellH = 88;

@implementation RABookMallHeaderItemModel 

@end

@interface RABookMallHeaderView ()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
ZYBannerViewDataSource,
ZYBannerViewDelegate,
KAAdNativeDelegate
>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray<RABookMallHeaderItemModel *> *dataSources;

@property (nonatomic, strong) ZYBannerView *banner;

@property (nonatomic, strong) UIView *adContainerView;

#pragma mark - Native广告
@property (nonatomic, strong) KAAdNative *ad;

@end

@implementation RABookMallHeaderView

#pragma mark - LifeCycle
- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self createViews];
  }
  return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
  self = [super initWithCoder:coder];
  if (self) {
    [self createViews];
  }
  return self;
}

- (void)layoutSubviews {
  [super layoutSubviews];
  
}

- (void)setModels:(NSArray<RABookFaceModel *> *)models {
  _models = models;
  
  [self.banner reloadData];
}

#pragma mark - CreateViews
- (void)createViews {
  self.backgroundColor = [UIColor whiteColor];
  
  [self addSubview:self.collectionView];
  [self setupBanner];
  
  [self.banner mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.right.left.mas_equalTo(0);
    make.height.mas_equalTo(kScreenWidth * 0.6);
  }];
  
  [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.right.left.mas_equalTo(0);
    make.height.mas_equalTo(CellH);
    make.top.mas_equalTo(self.banner.mas_bottom);
  }];
  
  self.ad = [[KAAdNative alloc] initWithSlot:@"QdADnkye" delegate:self];
  [self.ad load];
}

- (void)setupBanner {
  // 初始化
  self.banner = [[ZYBannerView alloc] init];
  self.banner.dataSource = self;
  self.banner.delegate = self;
  self.banner.autoScroll = YES;
  self.banner.shouldLoop = YES;
  [self addSubview:self.banner];
}

#pragma mark - LazyLoad
- (UIView *)adContainerView {
  if (!_adContainerView) {
    _adContainerView = [[UIView alloc] init];
    _adContainerView.backgroundColor = UIColorHex(ebebeb);
  }
  return _adContainerView;
}

#pragma mark - ZYBannerViewDataSource
// 返回 Banner 需要显示 Item(View) 的个数
- (NSInteger)numberOfItemsInBanner:(ZYBannerView *)banner {
  RABookFaceModel *curModel = [self.models firstObject];
  if (curModel && curModel.children && curModel.children.count > 0) {
    return curModel.children.count + 1;
  }
  
  return 1;
}

// 返回 Banner 在不同的 index 所要显示的 View (可以是完全自定义的v iew, 且无需设置 frame)
- (UIView *)banner:(ZYBannerView *)banner viewForItemAtIndex:(NSInteger)index {
  
  if (index == 0) {
    return self.adContainerView;
  }
  else {
    // 取出数据
    RABookFaceModel *curModel = [self.models firstObject];
    RABookFaceModel *model = [curModel.children objectAtIndex:index - 1];
    
    // 创建将要显示控件
    UIImageView *imageView = [[UIImageView alloc] init];
    
    // /api/server/file/imgView/http://res.cjzww.com/image/bdimages/2018-07-02/NvIndex2016_rank03_3.jpg?v=1530857682
    
    if (model.iconUrl && [model.iconUrl hasPrefix:@"http:"]) {
      [imageView sd_setImageWithURL:[NSURL URLWithString:model.iconUrl] placeholderImage:[UIImage imageWithColor:UIColorHex(ebebeb)]]; // @"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3252727510,3154347620&fm=200&gp=0.jpg"
    }
    else {
      
      NSRange range = [model.iconUrl rangeOfString:@"http:"];
      NSString *newUrl = [model.iconUrl substringFromIndex:range.location];
      [imageView sd_setImageWithURL:[NSURL URLWithString:newUrl] placeholderImage:[UIImage imageWithColor:UIColorHex(ebebeb)]]; // @"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3252727510,3154347620&fm=200&gp=0.jpg"
    }
    imageView.userInteractionEnabled = YES;
    [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
      [self jump:model];
    }]];
    
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    return imageView;
  }
  
}

- (void)jump:(RABookFaceModel *)model {
  
  if (self.jumpToBookDetail) {
    self.jumpToBookDetail(model);
  }
  
}


#pragma mark - KAAdNativeDelegate
// 广告请求成功
- (void)nativeAdRequestCompletedWithAd:(nonnull KAAdNative *)nativeAd {
  
  UIView *primaryView = [nativeAd primiaryViewOfSize:CGSizeMake(kScreenWidth, kScreenWidth * (640.0 / 960.0))];
  [self.adContainerView addSubview:primaryView];
  [self.banner reloadData];
  
  [nativeAd nativeAdRenderedWithView:primaryView]; // 上报广告展示
}

// 广告请求失败
- (void)nativeAdRequestFailedForSlot:(nonnull NSString *)nativeAdSlot
                           withStatus:(nonnull NSError *)nativeAdStatus {
  [self.ad load];
}

- (void)nativeAdRequestFailedWithAd:(nonnull KAAdNative *)nativeAd
                          withStatus:(nonnull NSError *)nativeAdStatus {}

#pragma mark - ZYBannerViewDelegate
// 在这里实现点击事件的处理
- (void)banner:(ZYBannerView *)banner didSelectItemAtIndex:(NSInteger)index {
  NSLog(@"点击了第%ld个项目", (long)index);
}

- (void)banner:(ZYBannerView *)banner didScrollToItemAtIndex:(NSInteger)index {
  NSLog(@"滚动到第%ld个项目", (long)index);
}

#pragma mark - Lazyload
- (UICollectionView *)collectionView {
  if (!_collectionView) {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = self.backgroundColor;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.bounces = YES;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [_collectionView registerClass:RABookMallHeaderCell.class forCellWithReuseIdentifier:NSStringFromClass(RABookMallHeaderCell.class)];
  }
  return _collectionView;
}

- (NSMutableArray<RABookMallHeaderItemModel *> *)dataSources {
  if (!_dataSources) {
    _dataSources = [NSMutableArray array];
    [_dataSources addObjectsFromArray:[self sourceArr]];
  }
  return _dataSources;
}

- (NSArray<RABookMallHeaderItemModel *> *)sourceArr {
  
  if (_type == 0) {
    RABookMallHeaderItemModel *model = [RABookMallHeaderItemModel new];
    model.title = @"分类";
    model.titleImg = @"bookmall_category";
    model.jId = @"0";
    
    RABookMallHeaderItemModel *model1 = [RABookMallHeaderItemModel new];
    model1.title = @"穿越";
    model1.titleImg = @"bookmall_through";
    model1.jId = @"3";
    
    RABookMallHeaderItemModel *model2 = [RABookMallHeaderItemModel new];
    model2.title = @"都市";
    model2.titleImg = @"bookmall_city";
    model2.jId = @"12";
    
    RABookMallHeaderItemModel *model3 = [RABookMallHeaderItemModel new];
    model3.title = @"玄幻";
    model3.titleImg = @"bookmall_fantasy";
    model3.jId = @"18";
    
    return @[model, model1, model2, model3];
  }
  else if (_type == 1) {
    RABookMallHeaderItemModel *model = [RABookMallHeaderItemModel new];
    model.title = @"都市";
    model.titleImg = @"bookmall_city";
    model.jId = @"12";
    
    RABookMallHeaderItemModel *model1 = [RABookMallHeaderItemModel new];
    model1.title = @"古言";
    model1.titleImg = @"bookmall_oldlauage";
    model1.jId = @"8";
    
    RABookMallHeaderItemModel *model2 = [RABookMallHeaderItemModel new];
    model2.title = @"现言";
    model2.titleImg = @"bookmall_nowlauage";
    model2.jId = @"7";
    
    RABookMallHeaderItemModel *model3 = [RABookMallHeaderItemModel new];
    model3.title = @"穿越";
    model3.titleImg = @"bookmall_through";
    model3.jId = @"3";
    
    return @[model, model1, model2, model3];
  }
  else if (_type == 2) {
    RABookMallHeaderItemModel *model = [RABookMallHeaderItemModel new];
    model.title = @"现言";
    model.titleImg = @"bookmall_nowlauage";
    model.jId = @"7";
    
    RABookMallHeaderItemModel *model1 = [RABookMallHeaderItemModel new];
    model1.title = @"都市";
    model1.titleImg = @"bookmall_city";
    model1.jId = @"12";
    
    RABookMallHeaderItemModel *model2 = [RABookMallHeaderItemModel new];
    model2.title = @"玄幻";
    model2.titleImg = @"bookmall_fantasy";
    model2.jId = @"18";
    
    RABookMallHeaderItemModel *model3 = [RABookMallHeaderItemModel new];
    model3.title = @"仙侠";
    model3.titleImg = @"bookmall_hero";
    model3.jId = @"17";
    
    return @[model, model1, model2, model3];
  }
  
  return @[];
}

- (NSArray<RABookFaceModel *> *)models {
  if (!_models) {
    _models = @[];
  }
  return _models;
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  
  return self.dataSources.count;
  
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  
  RABookMallHeaderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(RABookMallHeaderCell.class) forIndexPath:indexPath];
  
  cell.itemModel = [self.dataSources objectAtIndex:indexPath.item];
  
  return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  
  RABookMallHeaderItemModel *itemModel = [self.dataSources objectAtIndex:indexPath.item];
  
  if (self.clickedCallback) {
    self.clickedCallback(itemModel);
  }
  
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  
  CGFloat w = (kScreenWidth - 0 * 10.f) / 4;
  CGFloat h = CellH;
  
  return CGSizeMake(w, h);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
  return 0.f;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
  return 0.f;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
  return UIEdgeInsetsMake(0, 0, 0, 0);
}

@end
